<template>
  <view class="business-form">
    <view class="form-header">
      <view class="header-title">{{ isEdit ? (editId ? '编辑商家信息' : '新增商家信息') : '商家详情' }}</view>
      <view v-if="!isEdit" class="edit-btn" @tap="toggleEdit">编辑</view>
    </view>

    <!-- 表单项 -->
    <view class="form-item">
      <view class="label">店铺名称</view>
      <input
        class="input"
        type="text"
        placeholder="请填写店铺名称"
        v-model="businessForm.name"
        :disabled="!isEdit"
      />
    </view>

    <view class="form-item">
      <view class="label">联系人</view>
      <input
        class="input"
        type="text"
        placeholder="请填写联系人姓名"
        v-model="businessForm.contacts"
        :disabled="!isEdit"
      />
    </view>

    <view class="form-item">
      <view class="label">联系电话</view>
      <input
        class="input"
        type="number"
        maxlength="11"
        placeholder="请输入联系电话"
        v-model="businessForm.phone"
        :disabled="!isEdit"
      />
    </view>

    <view class="form-item">
      <view class="label">店铺地址</view>
      <textarea
        class="textarea"
        placeholder="请输入详细地址"
        v-model="businessForm.address"
        :disabled="!isEdit"
      />
      <!-- 地图选择按钮 -->
      <view v-if="isEdit" class="map-picker" @tap="openMapPicker">
        <text class="icon">📍</text>
        <text class="text">地图选点</text>
      </view>
    </view>

    <!-- 经纬度信息 -->
    <view class="form-item" v-if="isEdit || (businessForm.latitude && businessForm.longitude)">
      <view class="label">位置信息</view>
      <view class="location-info">
        <view class="location-item">
          <text class="location-label">经度：</text>
          <input
            class="location-input"
            type="text"
            v-model="businessForm.longitude"
            :disabled="!isEdit"
          />
        </view>
        <view class="location-item">
          <text class="location-label">纬度：</text>
          <input
            class="location-input"
            type="text"
            v-model="businessForm.latitude"
            :disabled="!isEdit"
          />
        </view>
      </view>
    </view>

    <!-- A券和B券余额 -->
    <view class="form-item">
      <view class="label">A券余额</view>
      <input
        class="input"
        type="digit"
        placeholder="请输入A券余额"
        v-model="businessForm.balanceA"
        :disabled="!isEdit"
      />
    </view>

    <view class="form-item">
      <view class="label">B券余额</view>
      <input
        class="input"
        type="digit"
        placeholder="请输入B券余额"
        v-model="businessForm.balanceB"
        :disabled="!isEdit"
      />
    </view>

    <!-- 保存按钮 -->
    <view v-if="isEdit" class="btn-wrapper">
      <nut-button class="save-btn" type="primary" @tap="saveBusinessInfo">保存</nut-button>
      <nut-button v-if="editId" class="cancel-btn" @tap="toggleEdit">取消</nut-button>
    </view>

    <!-- 地图选择器 -->
    <map
      v-if="showMap"
      class="map-container"
      :latitude="mapLocation.latitude"
      :longitude="mapLocation.longitude"
      :markers="markers"
      @tap="handleMapTap"
    >
      <cover-view class="map-toolbar">
        <cover-view class="map-confirm" @tap="confirmLocation">确定</cover-view>
        <cover-view class="map-cancel" @tap="cancelMap">取消</cover-view>
      </cover-view>
    </map>

    <!-- 地图加载遮罩 -->
    <view v-if="showMap" class="map-overlay"></view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import Taro from "@tarojs/taro";
import http from "@/utils/http";

// 获取页面参数
const router = Taro.getCurrentInstance().router;
const editId = ref(router?.params?.id || "");
const isEdit = ref(router?.params?.edit === "true" || !editId.value);

// 设置导航栏标题
Taro.setNavigationBarTitle({
  title: editId.value ? (isEdit.value ? "编辑商家信息" : "商家详情") : "新增商家信息",
});

// 商家表单数据
const businessForm = ref({
  id: "",
  name: "",
  contacts: "",
  phone: "",
  address: "",
  latitude: "",
  longitude: "",
  balanceA: 0,
  balanceB: 0,
});

// 地图相关状态
const showMap = ref(false);
const mapLocation = reactive({
  latitude: 30.27415,
  longitude: 120.15515,
});
const markers = ref([]);
const selectedLocation = ref(null);

// 切换编辑模式
function toggleEdit() {
  isEdit.value = !isEdit.value;
  if (!isEdit.value && editId.value) {
    // 如果取消编辑，重新加载数据
    loadBusinessInfo();
  }
}

// 加载商家信息
function loadBusinessInfo() {
  if (editId.value) {
    // 这里应该调用API获取商家信息
    // 模拟API调用
    setTimeout(() => {
      businessForm.value = {
        id: editId.value,
        name: "示例商家",
        contacts: "张三",
        phone: "13800138000",
        address: "广东省广州市天河区天河路385号",
        latitude: "23.125178",
        longitude: "113.327064",
        balanceA: 1000,
        balanceB: 500,
      };

      // 更新地图位置
      if (businessForm.value.latitude && businessForm.value.longitude) {
        mapLocation.latitude = parseFloat(businessForm.value.latitude);
        mapLocation.longitude = parseFloat(businessForm.value.longitude);
        updateMarker();
      }
    }, 500);

    // 实际API调用示例
    // http.get(`/api/business/${editId.value}`).then((res: any) => {
    //   if (res.code === 0 && res.data) {
    //     businessForm.value = res.data;
    //     // 更新地图位置
    //     if (businessForm.value.latitude && businessForm.value.longitude) {
    //       mapLocation.latitude = parseFloat(businessForm.value.latitude);
    //       mapLocation.longitude = parseFloat(businessForm.value.longitude);
    //       updateMarker();
    //     }
    //   }
    // });
  }
}

// 打开地图选择器
function openMapPicker() {
  // 如果已有经纬度，使用已有位置
  if (businessForm.value.latitude && businessForm.value.longitude) {
    mapLocation.latitude = parseFloat(businessForm.value.latitude);
    mapLocation.longitude = parseFloat(businessForm.value.longitude);
    showMap.value = true;
    updateMarker();
    return;
  }

  // 获取当前位置
  Taro.getLocation({
    type: "gcj02",
    success: (res) => {
      mapLocation.latitude = res.latitude;
      mapLocation.longitude = res.longitude;
      showMap.value = true;
      updateMarker();
    },
    fail: () => {
      // 如果获取位置失败，使用默认位置
      showMap.value = true;
      updateMarker();
    },
  });
}

// 更新地图标记
function updateMarker() {
  markers.value = [
    {
      id: 0,
      latitude: mapLocation.latitude,
      longitude: mapLocation.longitude,
      title: "选择的位置",
      width: 30,
      height: 30,
    },
  ];
}

// 处理地图点击事件
async function handleMapTap(e) {
  mapLocation.latitude = e.detail.latitude;
  mapLocation.longitude = e.detail.longitude;
  updateMarker();

  try {
    // 调用腾讯地图API进行逆地址解析
    const res = await Taro.request({
      url: "https://apis.map.qq.com/ws/geocoder/v1/",
      data: {
        location: `${e.detail.latitude},${e.detail.longitude}`,
        key: "YOUR_TENCENT_MAP_KEY", // 替换为您的腾讯地图API密钥
        get_poi: 0,
      },
    });

    if (res.data && res.data.status === 0) {
      selectedLocation.value = {
        address: res.data.result.address,
        latitude: e.detail.latitude,
        longitude: e.detail.longitude,
      };
    }
  } catch (error) {
    console.error("获取地址信息失败", error);
  }
}

// 确认选择的位置
function confirmLocation() {
  if (selectedLocation.value) {
    businessForm.value.address = selectedLocation.value.address;
    businessForm.value.latitude = selectedLocation.value.latitude.toString();
    businessForm.value.longitude = selectedLocation.value.longitude.toString();
  } else {
    businessForm.value.latitude = mapLocation.latitude.toString();
    businessForm.value.longitude = mapLocation.longitude.toString();
  }
  showMap.value = false;
}

// 取消地图选择
function cancelMap() {
  showMap.value = false;
}

// 保存商家信息
function saveBusinessInfo() {
  // 表单验证
  if (!businessForm.value.name) {
    Taro.showToast({ title: "请填写店铺名称", icon: "none" });
    return;
  }
  if (!businessForm.value.contacts) {
    Taro.showToast({ title: "请填写联系人", icon: "none" });
    return;
  }
  if (!businessForm.value.phone) {
    Taro.showToast({ title: "请填写联系电话", icon: "none" });
    return;
  }
  if (!businessForm.value.address) {
    Taro.showToast({ title: "请填写店铺地址", icon: "none" });
    return;
  }

  // 提交表单
  console.log("保存商家信息", businessForm.value);

  // 模拟API调用
  Taro.showLoading({ title: "保存中..." });
  setTimeout(() => {
    Taro.hideLoading();
    Taro.showToast({ title: "保存成功", icon: "success" });
    // 返回上一页
    setTimeout(() => {
      Taro.navigateBack();
    }, 1500);
  }, 1000);

  // 实际API调用示例
  // const apiUrl = editId.value ? `/api/business/${editId.value}` : '/api/business';
  // const method = editId.value ? 'put' : 'post';
  // http[method](apiUrl, businessForm.value).then((res: any) => {
  //   if (res.code === 0) {
  //     Taro.showToast({ title: "保存成功", icon: "success" });
  //     // 返回上一页
  //     setTimeout(() => {
  //       Taro.navigateBack();
  //     }, 1500);
  //   } else {
  //     Taro.showToast({ title: res.message || "保存失败", icon: "none" });
  //   }
  // }).catch(err => {
  //   Taro.showToast({ title: "网络错误，请重试", icon: "none" });
  // });
}

onMounted(() => {
  // 如果是编辑或查看模式，加载商家信息
  if (editId.value) {
    loadBusinessInfo();
  }
});
</script>

<style lang="scss">
.business-form {
  padding: 30rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
  box-sizing: border-box;

  .form-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;

    .header-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
    }

    .edit-btn {
      padding: 10rpx 30rpx;
      background-color: #ff6034;
      color: #fff;
      border-radius: 30rpx;
      font-size: 28rpx;
    }
  }

  .form-item {
    background-color: #fff;
    border-radius: 12rpx;
    padding: 30rpx;
    margin-bottom: 20rpx;

    .label {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 20rpx;
      font-weight: 500;
    }

    .input {
      width: 100%;
      height: 80rpx;
      font-size: 28rpx;
      color: #333;
      border-bottom: 1px solid #f5f5f5;
    }

    .textarea {
      width: 100%;
      height: 160rpx;
      font-size: 28rpx;
      color: #333;
      line-height: 1.5;
      margin-bottom: 20rpx;
      border: 1px solid #eee;
      padding: 10rpx;
      border-radius: 8rpx;
    }

    // 地图选择按钮样式
    .map-picker {
      display: flex;
      align-items: center;
      padding: 15rpx 20rpx;
      background-color: #f9f9f9;
      border-radius: 8rpx;
      border: 1px solid #eee;

      .icon {
        margin-right: 10rpx;
      }

      .text {
        font-size: 26rpx;
        color: #666;
      }
    }

    // 位置信息样式
    .location-info {
      display: flex;
      flex-direction: column;
      gap: 20rpx;

      .location-item {
        display: flex;
        align-items: center;

        .location-label {
          width: 100rpx;
          font-size: 26rpx;
          color: #666;
        }

        .location-input {
          flex: 1;
          height: 60rpx;
          font-size: 26rpx;
          color: #333;
          border: 1px solid #eee;
          border-radius: 6rpx;
          padding: 0 10rpx;
        }
      }
    }
  }

  .btn-wrapper {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
    padding: 0 30rpx;
    margin-top: 40rpx;

    .save-btn {
      width: 100%;
    }

    .cancel-btn {
      width: 100%;
      background-color: #f5f5f5;
      color: #666;
    }
  }

  // 地图容器样式
  .map-container {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1001;
    height: 100vh;
    width: 100vw;
  }

  // 地图工具栏
  .map-toolbar {
    position: absolute;
    bottom: 40rpx;
    left: 50%;
    transform: translateX(-50%);
    display: flex;
    justify-content: space-between;
    width: 80%;

    .map-confirm,
    .map-cancel {
      width: 300rpx;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      background: #ff6034;
      color: white;
      border-radius: 40rpx;
      font-size: 32rpx;
    }

    .map-cancel {
      background: #999;
    }
  }

  // 地图遮罩层
  .map-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    z-index: 1000;
  }
}
</style>